<?php
/**
 * api模块中间件
 */

namespace app\api\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use think\facade\Cache;
use Redis;

/**
 * 重复提交检查
 */
class ApiResubmitCheck implements MiddlewareInterface
{
    protected string $keyPrefix = 'api_resubmit_check_';

    public function process(Request $request, callable $handler): Response
    {
        // 如果当前方法要限制重复提交
        if (array_key_exists($request->request_url, API_RESUBMIT_CHECK)) {

            $key = $this->getThrottleKey();

            $cache_type = config('thinkcache.default');
            $cache_time = API_RESUBMIT_CHECK[$request->request_url];
            // 如果是redis
            if ($cache_type === 'redis') {
                /** @var Redis $redis */
                $redis  = Cache::store('redis')->handler();
                $number = $redis->incr($key);
                if ($number > 1) {
                    if ($number === 2) {
                        $redis->setex($key, $cache_time, 2);
                    }
                   return api_error('重复提交');
                }
            } else {
                $has = Cache::has($key);
                if ($has) {
               return api_error('重复提交');
                }
                Cache::set($key, 1, $cache_time);
            }
        }


        // 请求继续向洋葱芯穿越
        return $handler($request);
    }

    /**
     * 获取key
     * @return string
     */
    protected function getThrottleKey(): string
    {
        if (isset(request()->user)) {
            $key = $this->keyPrefix . sha1(request()->user->id . request()->request_url);
        } else {
            $key = $this->keyPrefix . sha1((request())->getRealIp() . (request())->header('user-agent'));
        }
        return $key;
    }
}
